import taobao_open
from django.db import connection
from taobao_open.api.base import TopException

from app import settings
from libs.db import DB


def sc_publisher_info_save(session, inviter_code):
    err = None
    if session == '':
        return None, '无效的授权信息'
    req = taobao_open.api.TbkScPublisherInfoSaveRequest()
    req.set_app_info(taobao_open.appinfo(settings.TBK_APP_KEY, settings.TBK_APP_SECRET))
    req.inviter_code = inviter_code
    req.info_type = 1
    api_resp = {}
    try:
        resp = req.getResponse(session)
        api_resp = resp.get('tbk_sc_publisher_info_save_response')
    except Exception as e:
        err = '获取淘宝客用户备案异常'
        print(err, e)
    return api_resp, err


def get_special_id(cursor, username, fields=None):
    if fields is None:
        fields = {
            'm': ['id'],
            'ta': ['special_id'],
        }
    left_join_tables = {
        'm': {'table': 'table_member', 'on': 'm.id=ta.mem_id'}
    }
    left_join_wheres = {
        'm': {
            'username': username,
        }
    }
    dh = DB('cs_tbk_auth', conn=cursor, table_as='ta')
    return dh.left_join(left_join_tables).one(fields, left_join_wheres)


def dg_optimus_material(form, member_id):
    err = None
    sub_code = None
    data = {'map_data': []}
    try:
        page_no = form.get_int('page_no', 1)
        page_size = form.get_int('page_size', 30)
        with connection.cursor() as cursor:
            db_tbk_auth = get_special_id(cursor, member_id)
        tbk_special_id = db_tbk_auth.get('special_id', '')
        if tbk_special_id != '':
            req = taobao_open.api.TbkDgOptimusMaterialRequest()
            req.set_app_info(taobao_open.appinfo(settings.TBK_APP_KEY, settings.TBK_APP_SECRET))
            req.special_id = tbk_special_id
            req.adzone_id = 111858100437
            req.material_id = 27160
            req.page_no = page_no
            req.page_size = page_size
            resp = req.getResponse()
            resp_data = resp.get('tbk_dg_optimus_material_response')
            resp_result_list = resp_data.get('result_list')
            map_data = resp_result_list.get('map_data')
            data = {'map_data': map_data}
        else:
            err = '请绑定淘宝客'
            sub_code = 'NEED_BIND_TBK'
            return data, err, sub_code
    except TopException as e:
        if e.errorcode == 15 and e.subcode == '50001':
            return data, err, sub_code
        else:
            if e.submsg:
                err = e.submsg
            else:
                err = '获取精选列表异常'
            return data, err, sub_code
    except Exception as e:
        err = '接口异常'
        print(err, e)
        return data, err, sub_code
    return data, err, sub_code


def dg_material_optional(form, member_id, keyword):
    err = None
    sub_code = None
    data = {'map_data': [], 'total': 0}
    try:
        page_no = form.get_int('page_no', 1)
        page_size = form.get_int('page_size', 30)
        if keyword == '':
            err = '无效的商品查询词'
            return data, err, sub_code
        with connection.cursor() as cursor:
            db_tbk_auth = get_special_id(cursor, member_id)
        tbk_special_id = db_tbk_auth.get('special_id', '')
        if tbk_special_id != '':
            req = taobao_open.api.TbkDgMaterialOptionalRequest()
            req.set_app_info(taobao_open.appinfo(settings.TBK_APP_KEY, settings.TBK_APP_SECRET))
            req.special_id = tbk_special_id
            req.adzone_id = 111858100437
            req.q = keyword
            req.page_no = page_no
            req.page_size = page_size
            resp = req.getResponse()
            resp_data = resp.get('tbk_dg_material_optional_response')
            resp_result_list = resp_data.get('result_list')
            map_data = resp_result_list.get('map_data')
            total_results = resp_data.get('total_results')
            data = {'map_data': map_data, 'total': total_results}
        else:
            err = '请绑定淘宝客'
            sub_code = 'NEED_BIND_TBK'
            return data, err, sub_code
    except TopException as e:
        if e.errorcode == 15 and e.subcode == '50001':
            return data, err, sub_code
        else:
            if e.submsg:
                err = e.submsg
            else:
                err = '搜索商品异常'
            return data, err, sub_code
    except Exception as e:
        err = '接口异常'
        print(err, e)
    return data, err, sub_code
